package com.et.machine.util

import android.util.Log
import com.et.logger.TAGS

class LabelChannel {

    fun initFoodChannelCount(box: Int, count: Int) {
        when (box) {
            9, 8, 7, 6 -> {
                boxChannelCountArray[9 - box] = count
                channelUseRoadCountArray[9 - box] = if ((count >= 80 || count % 10 == 0)) 10 else 8
            }
        }
    }


    fun channelLabel(box: Int, channel: Int) = when (box) {
        11 -> {
            String.format("%02d", channel)
        }
        9, 8, 7, 6 -> {
            foodLabel(box, channel)
        }
        1, 2, 3, 4, 5 -> {
            String.format("%d%02d", box, channel)
        }
        else -> {
            Log.d(TAGS.machine, "machine:box[$box] error")
            "unknown"
        }
    }

    private fun foodLabel(box: Int, channel: Int): String {
        var boxChannelCountMax = 0
        var boxChannelCountStartPosition = 0
        val channelIndex = 48 * (9 - box) + channel
        val row: Int
        val column: Int
        var shrLabelIfRoadUse8 = true
        // 60 48
        for (boxIndex in 0..3) {
            shrLabelIfRoadUse8 = channelUseRoadCountArray[boxIndex] == 8
            boxChannelCountStartPosition = boxChannelCountMax
            boxChannelCountMax += boxChannelCountArray[boxIndex]
            if (boxChannelCountMax <= 0) return "000"
            if (channelIndex <= boxChannelCountMax) {
                row =
                    (channelIndex - boxChannelCountStartPosition - 1) / channelUseRoadCountArray[boxIndex] + 1
                column =
                    (channelIndex - boxChannelCountStartPosition - 1) % channelUseRoadCountArray[boxIndex] + if (shrLabelIfRoadUse8) 1 else 0
                return "${9 - boxIndex}$row$column"
            }
        }
        return ""
    }


    companion object {
        private val boxChannelCountArray = intArrayOf(0, 0, 0, 0)
        private val channelUseRoadCountArray = intArrayOf(0, 0, 0, 0)

        @JvmStatic
        fun getInstance() = Holder.ins
    }

    object Holder {
        val ins = LabelChannel()
    }

}
